package com.heyige.facade;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heyige.dto.QuotaPackageDto;
import com.heyige.entity.QuotaOrder;
import com.heyige.entity.QuotaPackage;
import com.heyige.exception.BusinessException;
import com.heyige.exception.ErrorCode;
import com.heyige.service.QuotaOrderService;
import com.heyige.service.QuotaPackageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class QuotaPackageFacade {

    private final QuotaPackageService quotaPackageService;

    private final QuotaOrderService quotaOrderService;

    private final UserQuotaFacade userQuotaFacade;

    /**
     * 获取所有次数包
     *
     * @param page 当前页
     * @param size 页大小
     * @return 次数包列表
     */
    public IPage<QuotaPackage> getAllQuotaPackages(Integer page, Integer size) {
        IPage<QuotaPackage> pageObj = new Page<>(page, size);
        LambdaQueryWrapper<QuotaPackage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuotaPackage::getIsActive, true)
                .orderByAsc(QuotaPackage::getSortOrder);
        return quotaPackageService.page(pageObj, queryWrapper);
    }

    /**
     * 获取次数包详情
     *
     * @param id 次数包ID
     * @return 次数包详情
     */
    public QuotaPackage getQuotaPackage(Long id) {
        LambdaQueryWrapper<QuotaPackage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuotaPackage::getId, id)
                .eq(QuotaPackage::getIsActive, true);
        return quotaPackageService.getOne(queryWrapper);
    }

    /**
     * 创建次数包订单
     *
     * @param userId  用户ID
     * @param request 创建订单请求
     * @return 订单响应
     */
    @Transactional
    public QuotaPackageDto.OrderResponse createQuotaOrder(Long userId, QuotaPackageDto.CreateOrderRequest request) {
        // 检查次数包是否存在
        LambdaQueryWrapper<QuotaPackage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuotaPackage::getId, request.getQuotaPackageId())
                .eq(QuotaPackage::getIsActive, true);
        QuotaPackage quotaPackage = quotaPackageService.getOne(queryWrapper);
        if (quotaPackage == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "次数包不存在");
        }

        // 生成订单号
        String orderNo = generateOrderNo();

        // 创建订单
        QuotaOrder order = new QuotaOrder();
        order.setUserId(userId);
        order.setQuotaPackageId(request.getQuotaPackageId());
        order.setOrderNo(orderNo);
        order.setAmount(quotaPackage.getActualPrice());
        order.setQuota(quotaPackage.getQuota());
        order.setStatus(QuotaOrder.OrderStatus.PENDING.name());

        quotaOrderService.save(order);

        // 构建响应
        return buildOrderResponse(order, quotaPackage);
    }

    /**
     * 支付次数包订单
     *
     * @param orderId 订单ID
     * @param userId  用户ID
     * @param request 支付请求
     * @return 订单响应
     */
    @Transactional
    public QuotaPackageDto.OrderResponse payQuotaOrder(Long orderId, Long userId, QuotaPackageDto.PayRequest request) {
        // 检查订单是否存在且属于该用户
        LambdaQueryWrapper<QuotaOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(QuotaOrder::getId, orderId)
                .eq(QuotaOrder::getUserId, userId);
        QuotaOrder order = quotaOrderService.getOne(orderQueryWrapper);
        if (order == null) {
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在或无权限访问");
        }

        // 检查订单状态
        if (!order.getStatus().equals(QuotaOrder.OrderStatus.PENDING.name())) {
            throw new BusinessException(ErrorCode.ORDER_ALREADY_PAID, "订单状态不正确");
        }

        // 获取次数包信息
        LambdaQueryWrapper<QuotaPackage> packageQueryWrapper = new LambdaQueryWrapper<>();
        packageQueryWrapper.eq(QuotaPackage::getId, order.getQuotaPackageId())
                .eq(QuotaPackage::getIsActive, true);
        QuotaPackage quotaPackage = quotaPackageService.getOne(packageQueryWrapper);
        if (quotaPackage == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "次数包不存在");
        }

        // 更新订单状态
        order.setStatus(QuotaOrder.OrderStatus.PAID.name());
        order.setPaymentMethod(request.getPaymentMethod());
        order.setPaymentNo(request.getPaymentNo());
        order.setPaidTime(LocalDateTime.now());

        quotaOrderService.updateById(order);

        // 更新用户配额
        userQuotaFacade.addQuota(userId, order.getQuota());

        // 更新次数包销量
        quotaPackage.setSalesCount(quotaPackage.getSalesCount() + 1);
        quotaPackageService.updateById(quotaPackage);

        log.info("用户 {} 购买次数包 {}，订单 {}，获得配额 {}", userId, quotaPackage.getName(), orderId, order.getQuota());

        // 构建响应
        return buildOrderResponse(order, quotaPackage);
    }

    /**
     * 取消次数包订单
     *
     * @param orderId 订单ID
     * @param userId  用户ID
     */
    @Transactional
    public void cancelQuotaOrder(Long orderId, Long userId) {
        // 检查订单是否存在且属于该用户
        LambdaQueryWrapper<QuotaOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuotaOrder::getId, orderId)
                .eq(QuotaOrder::getUserId, userId);
        QuotaOrder order = quotaOrderService.getOne(queryWrapper);
        if (order == null) {
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在或无权限访问");
        }

        // 检查订单状态
        if (!order.getStatus().equals(QuotaOrder.OrderStatus.PENDING.name())) {
            throw new BusinessException(ErrorCode.ORDER_CANCELLED, "订单状态不正确，无法取消");
        }

        // 更新订单状态
        order.setStatus(QuotaOrder.OrderStatus.CANCELLED.name());
        order.setCancelTime(LocalDateTime.now());
        quotaOrderService.updateById(order);

        log.info("用户 {} 取消次数包订单 {}", userId, orderId);
    }

    /**
     * 获取用户的次数包订单列表
     *
     * @param userId 用户ID
     * @param page   当前页
     * @param size   页大小
     * @return 订单列表
     */
    public Page<QuotaPackageDto.OrderResponse> getUserQuotaOrders(Long userId, Integer page, Integer size) {
        Page<QuotaOrder> pageObj = new Page<>(page, size);
        LambdaQueryWrapper<QuotaOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuotaOrder::getUserId, userId)
                .orderByDesc(QuotaOrder::getCreatedAt);
        Page<QuotaOrder> orders = quotaOrderService.page(pageObj, queryWrapper);

        Page<QuotaPackageDto.OrderResponse> responsePage = new Page<>(page, size);
        responsePage.setTotal(orders.getTotal());
        // 这里应该将QuotaOrder转换为OrderResponse，但由于缺少相关逻辑，暂时返回空页面
        return responsePage;
    }

    /**
     * 获取订单详情
     *
     * @param orderId 订单ID
     * @param userId  用户ID
     * @return 订单响应
     */
    public QuotaPackageDto.OrderResponse getQuotaOrder(Long orderId, Long userId) {
        // 检查订单是否存在且属于该用户
        LambdaQueryWrapper<QuotaOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(QuotaOrder::getId, orderId)
                .eq(QuotaOrder::getUserId, userId);
        QuotaOrder order = quotaOrderService.getOne(orderQueryWrapper);
        if (order == null) {
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在或无权限访问");
        }

        // 获取次数包信息
        LambdaQueryWrapper<QuotaPackage> packageQueryWrapper = new LambdaQueryWrapper<>();
        packageQueryWrapper.eq(QuotaPackage::getId, order.getQuotaPackageId());
        QuotaPackage quotaPackage = quotaPackageService.getOne(packageQueryWrapper);
        if (quotaPackage == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "次数包不存在");
        }

        return buildOrderResponse(order, quotaPackage);
    }

    /**
     * 生成订单号
     *
     * @return 订单号
     */
    private String generateOrderNo() {
        return "Q" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 构建订单响应
     *
     * @param order        订单实体
     * @param quotaPackage 次数包
     * @return 订单响应
     */
    private QuotaPackageDto.OrderResponse buildOrderResponse(QuotaOrder order, QuotaPackage quotaPackage) {
        QuotaPackageDto.OrderResponse response = new QuotaPackageDto.OrderResponse();
        response.setId(order.getId());
        response.setUserId(order.getUserId());
        response.setOrderNo(order.getOrderNo());
        response.setStatus(order.getStatus());
        response.setAmount(order.getAmount());
        response.setQuota(order.getQuota());
        response.setPaidTime(order.getPaidTime());
        response.setCreatedAt(order.getCreatedAt());

        if (quotaPackage != null) {
            response.setQuotaPackageId(quotaPackage.getId());
            response.setQuotaPackageName(quotaPackage.getName());
            response.setQuotaPackageDescription(quotaPackage.getDescription());
            response.setOriginalPrice(quotaPackage.getPrice());
            response.setActualPrice(quotaPackage.getActualPrice());
            response.setDiscountPercentage(quotaPackage.getDiscountPercentage());
        }

        return response;
    }
}